package com.erli.exchange.common.aspect;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.erli.exchange.common.annotation.SysLog;
import com.erli.exchange.core.util.HttpContextUtils;
import com.erli.exchange.core.util.IPUtils;
import com.erli.exchange.dao.entity.SysLogEntity;


@Aspect
@Component
@Order(3)
public class SysLogAspect {
	
    private static Logger  logger = LoggerFactory.getLogger(SysLogAspect.class);
	
	@Pointcut("@annotation(com.erli.exchange.common.annotation.SysLog)")
	public void logPointCut() { 
		
	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point)  {
		long beginTime = System.currentTimeMillis();
		
		Object result = null;
		long time = 0;
        try {
    		//执行方法
    		result = point.proceed();
    		//执行时长(毫秒)
    		time = System.currentTimeMillis() - beginTime;
    		logger.info(JSON.toJSONString(getSysLog(point, time)));
        } catch(Throwable t) {
        	//执行时长(毫秒)
        	time = System.currentTimeMillis() - beginTime;
    		//保存系统日志
        	logger.error(JSON.toJSONString(getSysLog(point, time)));
        }
		return result;
	}

	private SysLogEntity getSysLog(ProceedingJoinPoint joinPoint, long time) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		SysLogEntity sysLog = new SysLogEntity();
		SysLog syslog = method.getAnnotation(SysLog.class);
		if(syslog != null){
			//注解上的描述
			sysLog.setOperation(syslog.value());
		}
		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLog.setMethod(String.format("%s.%s()", className, methodName));

		//请求的参数
		Object[] args = joinPoint.getArgs();
		String params = JSON.toJSONString(args);
		sysLog.setParams(params);
		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		sysLog.setIp(IPUtils.getIpAddr(request));
		sysLog.setTime(time);
		sysLog.setCreateDate(new Date());
		return sysLog;
	}
}
